<?php

/**
 * @Author: 网名
 * @Date:   2018-06-09 17:27:47
 * @Last Modified by:   网名
 * @Last Modified time: 2018-06-10 09:31:53
 */
namespace app\index\model;

use think\Model;
use think\Db;
class PackModel extends Model
{
    // 确定链接表名
    protected $name = 'pack';

    /**
     * 插入面单信息
     * @param $param
     */
    public function insertPack($param)
    {

      

        $oldname =substr($param['pack_file'], 1);
        $newname = str_replace('temporary', 'pdf', $oldname);
        
        // 启动事务
        Db::startTrans();
        try {
            //将pdf文件已到正式目录
            if ($param['filter']==1) {
                $param['pack_file'] = '/'.$newname;
                mvFile($oldname,$newname); 
            }
            $pack_id =  $this->insertGetId($param);
            $list = array();
            for ($i=0; $i < count($param['goods_name']) ; $i++) { 
                $list[$i]['pack_id'] = $pack_id;
                $list[$i]['goods_name'] = $param['goods_name'][$i];
                $list[$i]['goods_num'] = $param['goods_num'][$i];
                $list[$i]['goods_origin'] = $param['goods_origin'][$i];
                $list[$i]['express_code'] = trim($param['express_code'][$i]);
                $list[$i]['express_number'] = trim($param['express_number'][$i]);
                $list[$i]['create_time'] = $param['create_time'];
            }
            db('goods')->insertAll($list);
            Db::commit();

            
            // @unlink($oldname);//移除临时文件
            return ['status'=>1,'msg'=>'添加成功'];
            
        } catch (\Exception $e) {
            // 回滚事务
            
            Db::rollback();
            return ['status'=>0,'msg'=>$e->getMessage()];
           
        }
    }



    public function getPackByWhere($param){
        $page = $param['page']?$param['page']:1;
        $limit = $param['limit']?$param['limit']:10; //显示记录数
        $where['user_id'] = $param['user_id'];
        if ($param['pack_number']) {
            $where['pack_number'] = $param['pack_number'];
        }
        if ($param['pack_status']) {
             $where['pack_status'] = $param['pack_status'];
        }
        if ($param['platform_code']) {
            $where['platform_code'] = $param['platform_code'];
        }
        
        $row = $this->where($where)->page($page,$limit)->order('pack_id desc')->select();
        return $row;
    }

    public function getPackCount($param)
    {  
        
        $where = '';
        if (isset($param['user_id'])) {
            $where['user_id'] = $param['user_id'];
        }
        $count = db('pack')->where($where)->count();
        return $count;
    }

    public function getPackInfo($id){
       
        $info = $this->where(['pack_id'=>$id])->find();

        $info['goods'] = db('goods')->where(['pack_id'=>$info['pack_id']])->select();

        return $info;
    }

}